import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/empty_widget.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'root_category_list_item.dart';
import 'category_children_list_item.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/common/toast_util.dart';

class CategoriesPage extends StatefulWidget {
  int rootId = 0;
  Function onSelectTab;

  CategoriesPageState categoriesPageState;

  CategoriesPage({this.rootId = 0, this.onSelectTab});

  @override
  State<StatefulWidget> createState() {
    categoriesPageState =
        CategoriesPageState(rootId: this.rootId, onSelectTab: this.onSelectTab);
    return categoriesPageState;
  }

  initData(int rootId) {
    categoriesPageState.initData(rootId);
  }
}

class CategoriesPageState extends State<CategoriesPage> {
  double _topPadding;

  List categories = [];
  List categoryChildren = [];
  int currentPage = 1;
  int listTotalSize = 0;
  int selectedRootCategory = 0;

  int rootId = 0;
  Function onSelectTab;

  CategoriesPageState({this.rootId = 0, this.onSelectTab});

  @override
  void initState() {
    super.initState();
    _getCategoryList();
  }

  initData(int rootId) {
    this.rootId = rootId;
    _getCategoryList();
  }

  _getCategoryList() async {
    NetUtil.get(context, Api.categories, (data, message) {
      if (!mounted) return;

      int index = categories.indexWhere((v) {
        return v['id'] == rootId;
      });
      selectedRootCategory = index > -1 ? index : 0;

      setState(() {
        categories = data;
      });

      if (categories != null &&
          categories.length > selectedRootCategory &&
          categories[selectedRootCategory] != null &&
          categories[selectedRootCategory]["id"] > 0 &&
          "ShopCategory" == categories[selectedRootCategory]["type"]) {
        _getCategoryChildren(categories[selectedRootCategory]["id"]);
      } else if (categories != null &&
          categories.length > 0 &&
          "Brand" == categories[selectedRootCategory]["type"]) {
        _getBrandsWall();
      }
    });
  }

  _getCategoryChildren(int id) async {
    Map<String, String> params = {"parent_id": id.toString()};
    NetUtil.get(context, Api.shopCategories, (data, message) {
      if (!mounted) return;
      setState(() {
        categoryChildren = data;
      });
    }, params: params);
  }

  _getBrandsWall() {
    NetUtil.get(
      context,
      Api.pagesBrandsWall,
      (data, message) {
        if (!mounted) return;
        setState(() {
          categoryChildren = data;
        });
      },
    );
  }

  Widget renderRootCategoryRow(i) {
    return new RootCategoryListItem(categories[i], i == selectedRootCategory);
  }

  Widget buildRootCategories() {
    Widget list;
    if (categories.length > 0) {
      list = new ListView.builder(
        padding: EdgeInsets.only(top: 0.0),
        shrinkWrap: true,
        itemCount: categories.length,
        itemBuilder: (BuildContext context, int index) {
          return new InkWell(
              child: renderRootCategoryRow(index),
              onTap: () {
                if (!mounted) return;
                setState(() {
                  selectedRootCategory = index;
                });
                if ("ShopCategory" == categories[index]["type"]) {
                  _getCategoryChildren(categories[index]["id"]);
                } else if ("Brand" == categories[index]["type"]) {
                  _getBrandsWall();
                }
              });
        },
      );
    } else {
      list = EmptyWidget();
    }
    return list;
  }

  Widget renderCategoryChildrenRow(i) {
    return new CategoryChildrenListItem(
      categoryChildren[i],
      type: categories[selectedRootCategory]["type"].toString(),
    );
  }

  Widget buildCategoryChildren() {
    Widget list;
    if (categoryChildren.length > 0) {
      list = new ListView.builder(
          padding: EdgeInsets.only(top: 0.0),
          shrinkWrap: true,
          itemCount: categoryChildren.length,
          itemBuilder: (context, i) {
            return renderCategoryChildrenRow(i);
          });
    } else {
      list = EmptyWidget(
        tips: '没有符合条件的分类.',
        reloadAction: () {
          initData(this.rootId);
        },
      );
    }
    return list;
  }

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
  }

  @override
  Widget build(BuildContext context) {
    init();
    return new Column(
      children: <Widget>[
        new Container(
          padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
          color: ColorCommon.primaryColor,
          child: new Row(
            children: <Widget>[
              InkWell(
                onTap: () {
                  _scan();
                },
                child: Container(
                  child: new Image.asset('images/scan.png',
                      width: 20.0, height: 20.0),
                ),
              ),
              new Expanded(
                child: new GestureDetector(
                  child: new Container(
                    height: 28.0,
                    padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                    margin: const EdgeInsets.only(left: 20.0, right: 20.0),
                    decoration: new BoxDecoration(
                        color: ColorCommon.translucent1,
                        borderRadius: new BorderRadius.circular(100.0)),
                    child: new Row(
                      children: <Widget>[
                        new Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: new Image.asset(
                            'images/search.png',
                            width: 16.0,
                            height: 16.0,
                          ),
                        ),
                        new Text(
                          "搜索",
                          style: new TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                  onTap: () {
                    Navigator.of(context).pushNamed('/search_goods_page');
                  },
                ),
              ),
              InkWell(
                  onTap: () {
                    Navigator.of(context).pushNamed('/message_center_page');
                  },
                  child: new Container(
                    child: new Image.asset('images/message.png',
                        width: 20.0, height: 20.0),
                  )),
            ],
          ),
        ),
        Expanded(
          child: new Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Container(
                width: 100.0,
                child: buildRootCategories(),
              ),
              new Expanded(
                  child: new Container(
                padding: const EdgeInsets.only(bottom: 30.0),
                color: Colors.white,
                child: buildCategoryChildren(),
              ))
            ],
          ),
        ),
      ],
    );
  }

  Future _scan() async {
    ScanResult barcode;
    String errorStr;
    try {
      var options = ScanOptions(
        strings: {
          "cancel": "取消",
          "flash_on": "打开闪光灯",
          "flash_off": "关闭闪光灯",
        },
        android: AndroidOptions(
          useAutoFocus: true,
        ),
      );

      barcode = await BarcodeScanner.scan(options: options);
      int _pId = int.parse(barcode.rawContent);
      if (_pId != null && _pId > 0) {
        Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          return new GoodsDetailsPage(productId: _pId);
        }));
      }
      return;
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        errorStr = '未授权摄像头权限';
      } else {
        errorStr = 'Unknown error: $e';
      }
    } on FormatException {
      if (errorStr != null && errorStr.isNotEmpty) {
        errorStr = '数据解析有误, 请扫描正确的二维码';
      } else {
        return;
      }
    } catch (e) {
      errorStr = 'Unknown error: $e';
    }
    ToastUtil.showMessageToast(errorStr);
  }
}
